<template>
  <el-dialog
    title="登录"
    :visible.sync="dialogFormVisible"
    width="30%"
  >
    <el-form
      ref="loginformref"
      :model="loginform"
      :rules="loginformrules"
      class="form"
      :hide-required-asterisk="true"
    >
      <el-form-item
        prop="username"
        label="用户名"
        label-width="100px"
        class="loginlist"
      >
        <el-input v-model="loginform.username"></el-input>
      </el-form-item>
      <el-form-item
        prop="password"
        label="密码"
        label-width="100px"
        class="passwordlist"
      >
        <el-input
          v-model="loginform.password"
          type="password"
        ></el-input>
      </el-form-item>
      <el-form-item class="btns">
        <el-button
          type="primary"
          @click="login"
        >登录</el-button>
        <el-button
          type="info"
          @click="resetlogin"
        >重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
export default {
  name: 'Login',
  data () {
    return {
      dialogFormVisible: false,
      input: '',
      loginform: {
        username: '',
        password: ''
      },
      loginformrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  methods: {
    resetlogin () {
      this.$refs.loginformref.resetFields()
      this.username = ''
      this.password = ''
    },
    login () {
      this.$refs.loginformref.validate(async callback => {
        if (!callback) {
          this.$message({
            message: '请输入正确的登录格式',
            type: 'error',
            duration: 3000
          })
        } else {
          // 发起登录请求
          const result = await this.$http.post(
            'https://virtserver.swaggerhub.com/young-zy/Forum/0.0.1/user/login',
            this.loginform
          )
          console.log(result)
          console.log(result.data.Successful)
          if (result.data.Successful === true) {
            this.$message({
              message: '登录成功',
              type: 'success',
              duration: 3000
            })
            window.sessionStorage.setItem('token', result.data.token)
            setTimeout(window.location.reload(), 1000)
          } else if (result.data.Successful === false) {
            this.$message({
              message: result.data.Reason,
              type: 'error',
              duration: 3000
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login_box {
  background-color: #fff;
  position: absolute;
  left: 50%;
  transform: translate(-50%, 30%);
}

.loginlist {
  margin-top: 30px;
  padding-right: 70px;
}
.passwordlist {
  padding-right: 70px;
}

.btns {
  margin: 50px;
}
</style>
